<?php
namespace app\manage\controller;
use think\Controller;

class Base extends Controller
{
    private $pri = [];

    public function _initialize(){
        //验证是否登录
        if( !session('?admin.id') ){
            request()->isAjax() ? $this->layJson(1, '您还没有登录，请在登录之后进行操作') : $this->redirect('Show/login');
        }

        //验证session是否有效
        if(time()-session('admin.start_time') > config('session.expire') ){
            session_destroy();
            request()->isAjax() ? $this->layJson(1, '您的登录时长已超过一周，请重新登录') : $this->error('您的登录时长已超过一周，请重新登录', 'Show/login');
        }

        //验证该账号是否被禁用
        $whereAdmin['account'] = session('admin.account');
        $whereAdmin['password'] = session('admin.password');
        $whereAdmin['roleid'] = session('admin.role_id');
        $whereAdmin['status'] = 1;
        if( ! model('SystemAdmin')->where($whereAdmin)->count() ){
            request()->isAjax() ? $this->layJson(1, '该账号已被重新赋予权限，请重新登录') : $this->error('该账号已被重新赋予权限，请重新登录', 'Show/login');
        }

        //获取该账号权限
        $whereRole['id'] = session('admin.role_id');
        $priIdList = model('SystemRole')->where($whereRole)->value('pri_id_list_new'); //priList为1代表超级管理员

        $wherePrivilege = [];
        $priIdList!=='#' && $wherePrivilege['id'] = ['in', $priIdList];

        $priList = model('SystemPrivilegeNew')->where($wherePrivilege)->column('url');

        $allowList = [
            'Base/server',
            'Base/upload',
            'Index/index',
            'Index/welcome2',
            'Index/lock',
            'Index/feedback',
            'Index/history',
            'Index/quit',
        ];

        $this->pri = $allList = array_merge($priList, $allowList);
        $url = request()->controller().'/'.request()->action();

        if( !in_array($url, $allList) ){
            request()->isAjax() ? $this->layJson(1, '您没有权限访问，请联系管理员') : $this->error('您没有权限访问，请联系管理员');
        }

        //记录日志
        $dataRecord['admin_id'] = session('admin.id');
        $dataRecord['url'] = $url;
        $dataRecord['input'] = json_encode(input());
        model('SystemRecord')->save( $dataRecord );
    }

    //判断是否包含权限
    public function containPri($url){
        return in_array($url, $this->pri) ? true : false;
    }

    //lay-ui的格式返回
    protected function layJson($code=0, $msg='', $data=[]){
        $json['code'] = $code;
        $json['msg'] = $msg;
        $json['data'] = $data;
        echo json_encode($json);exit;
    }

    protected function layTable($code=0, $msg='', $data=[], $count=0, $params=[]){
        $json['code'] = $code;
        $json['msg'] = $msg;
        $json['data'] = $data;
        $json['count'] = $count;
        count($params) && $json['params'] = $params;
        echo json_encode($json);exit;
    }

    //获取区服
    public function server(){
        $serverId = !empty(input('server_id')) ? input('server_id') : 0;

        $where['game_id'] = input('game_id');
        $where['status'] = 1;
        $select = model('gameServer')->field('server_id, server_name')->where($where)->select();
        if($select){
            $data = collection($select)->toArray();

            $html = '<option value="">全服</option>';
            foreach($data as $k=>$v){
                $selected = $serverId==$v['server_id'] ? 'selected' : '';
                $html .= '<option '.$selected.' value="'.$v['server_id'].'">'.$v['server_id'].'：'.$v['server_name'].'</option>';
            }
           $this->layJson(0, '区服列表', $html);
        }else{
           $this->layJson(1, '区服列表为空');
        }
    }

    //上传文件
    public function upload(){
        $file = request()->file('file');

        switch ( input('name') ){
            case 'bag':
                $gameId = input('game_id');
                empty($gameId) && $this->layJson(1, '游戏ID不能为空');
                $uploadPath = ROOT_PATH.'uploads/bag/user/'. input('game_id') . '/';
                $uploadSize = ['size'=>'10485760'];
                break;
            case 'channel_bag':
                $gameId = input('game_id');
                $typeId = input('type_id');
                $addType = input('add_type');
                empty($gameId) && $this->layJson(1, '游戏ID不能为空');
                empty($typeId) && $this->layJson(1, '礼包类型不能为空');
                empty($addType) && $this->layJson(1, '添加类型不能为空');

                $whereChannelBag['add_type'] = $addType;
                $whereChannelBag['type_id'] = $typeId;
                $whereChannelBag['game_id'] = $gameId;
                $whereChannelBag['status'] = 1;
                if( model('ChannelBag')->where($whereChannelBag)->count() ){
                    $this->layJson(1, '已存在该游戏该类型礼包');
                }

                $channelBagType = changeValKey('ChannelBagType', 'id', 'type');
                $uploadPath = ROOT_PATH.'uploads/bag/channel/';
                $uploadSize = ['size'=>'10485760'];
                $customName = $gameId . '_' . transPinyin($channelBagType[$typeId]);
                break;
            case 'activity':
                $uploadPath = ROOT_PATH.'uploads/editor/activity/';
                $kunPath = 'editor/activity/';
                $uploadSize = ['size'=>'10485760'];
                break;
            case 'notice':
                $uploadPath = ROOT_PATH.'uploads/editor/notice/';
                $kunPath = 'editor/notice/';
                $uploadSize = ['size'=>'10485760'];
                break;
            case 'game_images':
                $uploadPath = ROOT_PATH.'uploads/game/images/' . input('game_id') . '/';
                $kunPath = 'game/images/' . input('game_id') . '/';
                $uploadSize = ['size'=>'10485760'];
                break;
            case 'game_icon':
                $uploadPath = ROOT_PATH.'uploads/game/icon/' . input('game_id') . '/';
                $kunPath = 'game/icon/' . input('game_id') . '/';
                $uploadSize = ['size'=>'10485760'];
                break;
            default: $this->layJson(1, '参数错误');
        }

        if(input('name')=='channel_bag'){
            $info = $file
                ->validate($uploadSize)
                ->move($uploadPath, $customName);
            $fileName = $info->getSaveName();
        }else{
            $info = $file
                ->validate($uploadSize) //b为单位，10M
                ->rule('uniqid')
                ->move($uploadPath);

            $fileName = $info->getSaveName();
            $filePath = $uploadPath . $info->getSaveName();
        }

        if( input('name')=='bag' ){
            //同步到接口服务器，追加不同步
            if( ! input('?append') ){
                $httpRs = curl_file('http://uc.miyuhaiwai.com/Curl/uploadBag', $filePath, input('game_id'));
                $dataRs = json_decode($httpRs, true);
                if($dataRs['result']==0){
                    $this->layJson(1, $dataRs['msg']);
                }
            }
            $params = ['src' => $fileName];
        }else if(input('name')=='channel_bag'){
            $params = ['src' => $fileName];
        }else{
            $fileKun = $kunPath . $info->getSaveName();
            action('KsyunUpload/put', ['miyu-game-img-bucket', $filePath, $fileKun]);
            $params = ['src' => config('ksyun_domain').'/'.$fileKun];
        }

        return $info ? $this->layJson(0, '上传成功', $params) : $this->layJson(1, $file->getError());
    }
}